package blogs.eidos.cloud.framework.core.interceptor;

import lombok.extern.slf4j.Slf4j;
import net.bigdata.cloud.framework.core.annotation.ExtApiIdempotent;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 接口幂等性拦截器 写在需要保证Controller上
 *
 * @author ： Eidos
 * @date ：Created in 2021/4/12
 * @description：
 * @modified By：
 * @version: 1.0
 */
@Slf4j
public class ApiIdempotentInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        ExtApiIdempotent methodAnnotation = method.getAnnotation(ExtApiIdempotent.class);
        if (methodAnnotation != null) {
            // 幂等性校验, 校验通过则放行, 校验失败则抛出异常, 并通过统一异常处理返回友好提示
            return apiIdempotent();
        }else{
            return true;
        }

    }

    private Boolean apiIdempotent() {
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }


}